var express = require("express"),
	app = express(),
	server = require("http").createServer(app),
	port = parseInt(process.env.PORT,10) || 8000;


var http = require('http');


//app.use(express.bodyParser());
app.configure(function(){
	app.use(express.methodOverride());
	app.use(express.bodyParser());
	app.use(express.static(__dirname+'/public/'));
	app.use(express.errorHandler({
		dumpExceptions: true,
		showStack: true
	}));
});


app.get('/', function(req, res){
  res.redirect("/login.html");
});

var roomCounter = 0;
var globalData = {
	rooms:[{
		name: "FirstRoom",
		id: roomCounter++,
		users: ["dabs","sigga","joi"],
		messages: [] }],
};


var openConnections = [];

app.post('/login', function (req, res) {
	res.writeHead(302, {
  	'Location': '/'
  	//add other headers here...
	});
	res.end();
});

app.post('/room/create', function(req,res){
	var post = req.body;
	var room ={
		name: post.channel,
		id: roomCounter++
	};
	globalData.rooms.push(room);
	console.log(post.channel);
	res.json(globalData);
})

app.get('/room/:id', function(req,res){
	data = "Not found";
	for(var i = 0; i<globalData.rooms.length;i++){
		if(globalData.rooms[i].id == req.params.id){
			data =  globalData.rooms[i];
			break;
		}
		
	}

	res.json(data);

})

app.get("/room/:id/update",function(req,res){
	req.socket.setTimeout(Infinity);
		res.writeHead(200, {
	        'Content-Type': 'text/event-stream',
	        'Cache-Control': 'no-cache',
	        'Connection': 'keep-alive'
	    });
	    
	    openConnections.push(res);
	    res.write('\n');

	    req.on("close", function() {
	        var toRemove;
	        for (var j =0 ; j < openConnections.length ; j++) {
	            if (openConnections[j] == res) {
	                toRemove =j;

	                break;
	            }
	        }
	        openConnections.splice(j,1);
	        
	    });
});

app.get("/rooms",function(req,res){
	//res.json(res.UserId);
	console.log(req.socket.username);
	
  	res.json(globalData);
});



setInterval(function() {

    // we walk through each connection
    openConnections.forEach(function(resp) {
        var d = new Date();
        resp.write('id: ' + d.getMilliseconds() + '\n');
        resp.write('data:' + "asdf" +   '\n\n'); // Note the extra newline
    });
 
}, 1000);
//app.post(..)

app.listen(port);